package org.vergil.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.vergil.interceptor.CommonInterceptor;
import org.vergil.interceptor.JwtInterceptor;
import org.vergil.interceptor.LogInterceptor;
import org.vergil.websocket.MyWebSocketHandler;

/**
 * Created by vergil on 5/6/17.
 */
@Configuration
@EnableWebSocket
public class WebConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {

    /***
     * 日志拦截器
     */
    @Bean
    public LogInterceptor loginInterceptor() {
        return new LogInterceptor();
    }

    @Bean
    public CommonInterceptor commonInterceptor() {
        return new CommonInterceptor();
    }

    @Bean
    public JwtInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }

    /**
     * 注册拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(commonInterceptor());
        registry.addInterceptor(loginInterceptor());
        registry.addInterceptor(jwtInterceptor()).excludePathPatterns("/login","/register","/index","/test");
    }

    @Bean
    public MyWebSocketHandler myWebSocketHandler(){
        return new MyWebSocketHandler();
    }


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(myWebSocketHandler(),"/socket").setAllowedOrigins("*");
        webSocketHandlerRegistry.addHandler(myWebSocketHandler(),"/socket").setAllowedOrigins("*").withSockJS();
    }
}
